float4x4 g_matWorldViewProject;
float4 g_vCamLookAtDir;
float4 g_vSelectionColor;
float g_fSeaLevelHeight;
float g_fTime;

texture BorderDiffuse;
sampler MeshBorderDiffuse = sampler_state
{
	Texture = <BorderDiffuse>;
	MagFilter = LINEAR;
	MipFilter = LINEAR;
	MinFilter = LINEAR;
	AddressU = Wrap;
	AddressV = Clamp;
};

struct VS_INPUT
{
	float3 Position			: POSITION;
	float2 UV				: TEXCOORD0;
};

struct VS_OUTPUT
{
	float4 Position			: POSITION;
	float3 PrePos			: TEXCOORD0;
	float2 UV				: TEXCOORD1;
};

VS_OUTPUT RenderSceneVS( VS_INPUT Input )
{
	VS_OUTPUT Output = ( VS_OUTPUT )0;
	float4 pos = float4( Input.Position, 1.f );
	float fClampHeight = saturate(( g_fSeaLevelHeight - Input.Position.y ) * 10000 );
	pos.y = fClampHeight * g_fSeaLevelHeight + ( 1.0f - fClampHeight ) * pos.y;
	Output.PrePos = pos.xyz;
	
	// 在摄像机空间移动Z值 避免被地表阻挡
	float4 vDistortedPos = pos - g_vCamLookAtDir * 0.05f;
	pos = mul( pos, g_matWorldViewProject );
	float fNewZ = dot( vDistortedPos, float4( g_matWorldViewProject[0][2], g_matWorldViewProject[1][2], g_matWorldViewProject[2][2], g_matWorldViewProject[3][2] ));
	Output.Position = float4( pos.xy, fNewZ, pos.w );
	
	Output.UV = Input.UV;
	return Output;
}

float4 RenderScenePS( VS_OUTPUT Input ) : COLOR0
{
	float4 vColor = tex2D( MeshBorderDiffuse, float2( Input.UV.x * 0.1f, Input.UV.y ));
	vColor.a *= 3.5f;
	float vPulseFactor = saturate( smoothstep( 0.0f, 1.0f, ( 0.8f - abs(Input.UV.y - 0.5f )) + sin( g_fTime * 2.5f) * 0.15f )) * g_vSelectionColor.a;
	vColor.rgb = saturate( vColor.rgb + g_vSelectionColor.rgb * saturate( vPulseFactor - vColor.a * 0.35f ));
	vColor.a = max( vColor.a, vPulseFactor - 0.2f );
	return vColor;
}

technique Border
{
	pass P0
	{
		AlphaBlendEnable = true;
		SrcBlend = SrcAlpha;
		DestBlend = InvSrcAlpha;
		AlphaTestEnable = false;
		FillMode = Solid;
		VertexShader = compile vs_3_0 RenderSceneVS();
		PixelShader = compile ps_3_0 RenderScenePS();
	}
}
